package org.lightrpc.server.http;

import org.lightrpc.DummyService;
import org.lightrpc.LightRpcInitializationFailed;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;

public class EmbeddedServer {
	
	private static Server server;
	
	/**
	 * This is the main method for the starting LightRPC
	 * First parameter should be the port where LightRPC starts,
	 * then follow the fully qualified names of classes to be
	 * exposed. If no params are provided Server binds to port
	 * 8080 and starts up a DummyService {@link DummyService}
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		String[] classes  = new String[]{"org.lightrpc.DummyService"};
		int port = 8080;
		if (args.length > 2){
			port = Integer.parseInt(args[0]);
			for (int i = 1; i < args.length; i++) {
				classes[i-1] = args[i];
			} 
		}
		startServer(port, classes);
	}
	
	/**
	 * This method starts the webservice servlet and binds
	 * it to the appropriate port. WebService classname should be provided
	 * TODO:path should be configurable
	 * @param port
	 * @param classNames
	 * @throws Exception 
	 */
	public static void startServer(int port, String... classNames) throws Exception{
		server = new Server(port);
		Context root = new Context(server,"/",Context.SESSIONS);
		//TODO:this will come from the args!Remove, when finished with testing
		if (classNames.length == 0){
			throw new LightRpcInitializationFailed("No webservices defined at startup. " +
					"Please provide necessary class names");
		}
		root.getServletContext().setAttribute(ServletFrontController.WEBSERVICES, classNames);
		root.addServlet(new ServletHolder(new ServletFrontController()), "/*");
		server.start();
	}
	
	public static void shutdownServer(){
		try {
			server.stop();
		} catch (Exception e) {
			e.printStackTrace();
		}
		server.destroy();
		
	}
	
	

}
